package org.xczy.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.xczy.core.entity.Menu;
import org.xczy.core.service.MenuService;
import org.xczy.core.mapper.MenuMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author Administrator
* @description 针对表【menu(菜单表)】的数据库操作Service实现
* @createDate 2023-05-07 13:34:26
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService{

  @Resource
  private MenuMapper menuMapper;

  @Override
  public List<Menu> getMenuListByUserId(Integer userId) {
//    // 一级菜单
    List<Menu> menuList = menuMapper.getMenuListByUserId(userId, 0);
    // 二级菜单
    setMenuChildrenByUserId(userId, menuList);
    return menuList;
  }

  @Override
  public List<Menu> getAllMenu() {
    // 一级菜单
    LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Menu::getParentId, 0);
    List<Menu> menuList = this.list(wrapper);
    // 填充子菜单
    setMenuChildren(menuList);
    return menuList;
  }

  private void setMenuChildren(List<Menu> menuList) {
    if (menuList != null) {
      for (Menu menu : menuList) {
        LambdaQueryWrapper<Menu> subWrapper = new LambdaQueryWrapper<>();
        subWrapper.eq(Menu::getParentId, menu.getMenuId());
        List<Menu> subMenuList = this.list(subWrapper);
        menu.setChildren(subMenuList);
        // 递归
        setMenuChildren(subMenuList);
      }
    }
  }

  private void setMenuChildrenByUserId(Integer userId, List<Menu> menuList) {
    if (menuList != null) {
      for (Menu menu : menuList) {
        List<Menu> subMenuList = menuMapper.getMenuListByUserId(userId, menu.getMenuId());
        menu.setChildren(subMenuList);
        // 递归
        setMenuChildrenByUserId(userId, subMenuList);
      }
    }
  }
}




